﻿using Newtonsoft.Json;
using Sunny.UI;
using System.Collections.Generic;
using System.ComponentModel;
using System.DirectoryServices.ActiveDirectory;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using WinApp.i18n;
using WinApp.Model;
using WinApp.Until;
using WinApp.ViewModel;
using GroupBox = System.Windows.Forms.GroupBox;
using TextBox = System.Windows.Forms.TextBox;

namespace WinApp.View
{
    public partial class MyCourses : UIPage
    {
        public WinApp _parent { get; set; }
        public CourseList _courseListIncomplete { get; set; }
        public CourseList _courseListCompleted { get; set; }
        public CourseList _courseListAll { get; set; }
        public SearchMyCourseSessionEntity _searchMyCourseSessionEntity = new SearchMyCourseSessionEntity
        {
            StandardCourseType = 2,
            LearningStatuStr = 2,
            PageCondition = new Model.PageCondition()
            {
                PageIndex = 1,
                PageSize = 10,
                SortConditions = new List<Model.SortCondition> { new Model.SortCondition() { SortField = "BeginTime", ListSortDirection = Model.ListSortDirection.Ascending } }
            }
        };
        public MyCourses()
        {
            InitializeComponent();
            this.Text = Language.GetLang("myCourse");
            uiTabControl1.RemoveAllPages();


            tabPage1.Text = Language.GetLang("incomplete");
            //this.tabPage1.AutoScroll = true;
            //this.tabPage1.MouseWheel += TabPage_MouseWheel;
            if (_courseListIncomplete == null)
                _courseListIncomplete = new CourseList();
            _courseListIncomplete.Dock = DockStyle.Fill;
            tabPage1.Controls.Add(_courseListIncomplete);

            tabPage2.Text = Language.GetLang("completed");
            //bPage2.AutoScroll = true;
            //tabPage2.MouseWheel += TabPage_MouseWheel;
            if (_courseListCompleted == null)
                _courseListCompleted = new CourseList();
            _courseListCompleted.Dock = DockStyle.Fill;
            tabPage2.Controls.Add(_courseListCompleted);

            tabPage3.Text = Language.GetLang("all");
            //tabPage3.AutoScroll = true;
            //tabPage3.MouseWheel += TabPage_MouseWheel;
            if (_courseListAll == null)
                _courseListAll = new CourseList();
            _courseListAll.Dock = DockStyle.Fill;
            tabPage3.Controls.Add(_courseListAll);

        }

        private void MyCourses_Load(object sender, EventArgs e)
        {

            //默认打开第一个tabPage,并且查询
            uiTabControl1.SelectTab(0);
            _courseListIncomplete._searchMyCourseSessionEntity.LearningStatu = new string[] { "1", "0" };
            _courseListIncomplete.LoadPanellData();

            //LoadPanellData();
            //System.Threading.Thread.Sleep(5000); // 模拟耗时操作

        }

        public void LoadPanellData()
        {
            LoadingHelper.ShowLoadingScreen();//显示
            // 进行耗时操作，例如加载接口
            var result = WebApiHelper.PostWebAPI<PageDataRow>("api/Admin/Enrollment/ReadByMyEnrollment", _searchMyCourseSessionEntity);
            if (result.Total <= 0)
                return;
            List<MyCourseSessionEntityOutputDto> DataRows = JsonConvert.DeserializeObject<List<MyCourseSessionEntityOutputDto>>(result.Rows.ToString());
            if (DataRows == null || DataRows.Count <= 0)
                return;
            //this.panel1.Controls.Clear();
            for (int i = 0; i < DataRows.Count; i++)
            {
                GroupBox gbox = new GroupBox();
                gbox.Width = 1065;
                gbox.Height = 140;
                gbox.Text = (i + 1).ToString();
                gbox.Tag = DataRows[i].CourseSessionId.ToString();
                gbox.Location = new Point(3, 12 + i * 140);
                gbox.Click += Gbox_Click;
                //this.panel1.Controls.Add(gbox);
                FillInPanell(gbox, DataRows[i]);
            }

            LoadingHelper.CloseForm();//关闭
        }

        private void Gbox_Click(object? sender, EventArgs e)
        {

            GroupBox clickGroupBox = sender as GroupBox;
            if (clickGroupBox == null)
                return;
            var CourseSessionId = clickGroupBox.Tag.ToString();
            _parent.SetNavMenulPageIndex(NavPageIndex.courseDetails, CourseSessionId);


        }

        public void FillInPanell(GroupBox gb, MyCourseSessionEntityOutputDto item)
        {
            var defaultCbtCover = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/book.png");
            if (!string.IsNullOrEmpty(item.SurfacePlot))
            {
                defaultCbtCover = FileHelper.LoadImageFromWebUriAsync(GlobalVariables.WebIp + "fileFolder/courseSurfaces/" + WebApiHelper._Tenancy + "/" + item.SurfacePlot);
            }

            PictureBox pictureBox = new PictureBox();
            pictureBox.Width = 107;
            pictureBox.Height = 107;
            pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox.Location = new Point(26, 18);
            pictureBox.Image = defaultCbtCover;
            gb.Controls.Add(pictureBox);

            UIAvatar uIAvatar = new UIAvatar();
            uIAvatar.AvatarSize = 35;
            uIAvatar.Width = 42;
            uIAvatar.Height = 37;
            uIAvatar.Shape = UIShape.Circle;
            uIAvatar.Symbol = 61465;
            uIAvatar.FillColor = Color.Transparent;
            uIAvatar.Location = new Point(965, 60);
            gb.Controls.Add(uIAvatar);

            UILabel lbTitle = new UILabel();
            lbTitle.Location = new Point(150, 18);
            lbTitle.Width = 500;
            lbTitle.Text = item.CourseSessionName;
            lbTitle.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbTitle);

            UILabel lbCourseUnit = new UILabel();
            lbCourseUnit.Location = new Point(150, 49);
            lbCourseUnit.Width = 200;
            string CourseUnitStr = Language.GetLang("courseUnit") + item.LessonCount;
            lbCourseUnit.Text = CourseUnitStr;
            gb.Controls.Add(lbCourseUnit);

            UILabel lbStatus = new UILabel();
            lbStatus.Location = new Point(150, 72);
            lbStatus.Width = 200;
            var statusStr = string.Empty;
            switch (item.LearningStatu)
            {
                case 1:
                    statusStr = Language.GetLang("incomplete");
                    lbStatus.ForeColor = Color.Orange;
                    break;
                case 2:
                    statusStr = Language.GetLang("completed");
                    lbStatus.ForeColor = Color.Green;
                    break;
                default:
                    statusStr = Language.GetLang("notStarted");
                    break;
            }
            lbStatus.Text = statusStr;
            lbStatus.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbStatus);

            UILabel lbTime = new UILabel();
            lbTime.Location = new Point(150, 103);
            lbTime.Width = 500;
            var timeStr = string.Empty;
            var beginTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.BeginTime), TimeZoneInfo.Local);
            timeStr = Language.GetLang("startTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            if (item.EndTime != null)
            {
                var endTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.EndTime), TimeZoneInfo.Local);
                timeStr += " - " + Language.GetLang("endTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            lbTime.Text = timeStr;
            gb.Controls.Add(lbTime);

            UILabel lbLearned = new UILabel();
            lbLearned.Location = new Point(900, 100);
            lbLearned.Width = 200;
            //lbLearned.TextAlign = ContentAlignment.MiddleCenter;
            lbLearned.ForeColor = Color.Red;
            var learnedStr = string.Empty;
            if (item.CumulativeLearningTime != null && item.CumulativeLearningTime > 0)
            {
                learnedStr = Language.GetLang("learned") + UtilHelper.DoubleTimeToString(item.CumulativeLearningTime);
            }
            lbLearned.Text = learnedStr;

            gb.Controls.Add(lbLearned);
        }



        private void TabPage_MouseWheel(object? sender, MouseEventArgs e)
        {
            //var vScrollPosition = panel1.VerticalScroll.Value;
            //if (vScrollPosition == panel1.VerticalScroll.Maximum - panel1.VerticalScroll.LargeChange + 1)
            //{
            //    //MessageBox.Show("已经滚动到底部");
            //    return;
            //}
        }

        private void panel1_Scroll(object sender, ScrollEventArgs e)
        {
            //var vScrollPosition = panel1.VerticalScroll.Value;
            //if (vScrollPosition == panel1.VerticalScroll.Maximum - panel1.VerticalScroll.LargeChange + 1)
            //{
            //    //MessageBox.Show("已经滚动到底部");
            //    return;
            //}
        }

        private void uiTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var tabControl = sender as TabControl;
            //MessageBox.Show(tabPage.ImageIndex.ToString());
            var currentPage = tabControl.SelectedTab;

            switch (tabControl.SelectedIndex)
            {
                case 0:
                    _courseListIncomplete._searchMyCourseSessionEntity.LearningStatu = new string[] { "1", "0" };
                    _courseListIncomplete.LoadPanellData();
                    break;
                case 1:
                    _courseListCompleted._searchMyCourseSessionEntity.LearningStatu = new string[] { "2" };
                    _courseListCompleted.LoadPanellData();
                    break;
                case 2:
                    _courseListAll._searchMyCourseSessionEntity.LearningStatu = new string[] { };
                    _courseListAll.LoadPanellData();
                    break;
                default:
                    break;
            }


            //Label label = new Label();
            //label.Text = "Test";
            //currentPage.Controls.Add(label);

            //string controlName = "panel1"; // 你要查找的控件的名称
            //Control[] foundControls = this.Controls.Find(controlName, true);

            //if (foundControls.Length > 0)
            //{
            //    Control myControl = foundControls[0]; // 取第一个找到的控件

            //    // 在此处使用找到的控件
            //    myControl.Text = "Found It!";
            //}
            //else
            //{
            //    MessageBox.Show("Control not found");
            //}
        }
    }
}
